package com.smartbone.security;

import java.io.IOException;
import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.apache.log4j.*;
@ManagedBean(name="loginBean")  
@RequestScoped
public class LoginBean implements Serializable {
    protected final Logger log = Logger.getLogger(LoginBean.class);
    
	private static final long serialVersionUID = 5130512624330203342L;

	public String loginAction() throws IOException, ServletException {
		if (log.isDebugEnabled()){
			log.debug("login");
		}
		
		String result = "";
		ExternalContext context = FacesContext.getCurrentInstance()
				.getExternalContext();
		RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
				.getRequestDispatcher("/j_spring_security_check");
		dispatcher.forward((ServletRequest) context.getRequest(),
				(ServletResponse) context.getResponse());
	    
		if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {
			
			Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			
			if (principal instanceof UserDetails) {
				result = "loginSuccess";
			} else {
				result = "loginFailed";
			}
		}else{
			result = "loginFailed";
		}
		FacesContext.getCurrentInstance().responseComplete();
		return result;
	}


}